﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation; 

namespace _12306Bot.Common
{
    public class CDN
    {
        /// <summary>
        /// 超时时间
        /// </summary>
        private const int iTimeLimit = 60;

        /// <summary>
        /// IP数组
        /// </summary>
        private String[] strArrIP;
        /// <summary>
        /// 当前IP数组下标
        /// </summary>
        private int IPIndex;
        /// <summary>
        /// IP数组长度
        /// </summary>
        private int IPCount;
        /// <summary>
        /// IP数组
        /// </summary>
        private SortedList<String, long> _sdIP;
        public SortedList<String, long> SdIP
        {
            get { return _sdIP; }
        }

        public CDN()
        {
            String strIP = "uuYPGPKEiJY3jevUYDcxYL3Q4twIveDcRQcpMoeHropMeNVF66a/4TKkLBEGg7ag+34R2d2ANtcmvuUeRzCnesWXE8GDD64SN0d35BrIRC9Widh6IyucbnA4XIzC/X8sqr1RMLoxPgie3A17geqay8mOE9sCqYd5cwWDgqEJyfi9vDUJgnJwGKmL0RaiN7suKyjAhUYr5JH0KvIKIn8KUrjO6cSq/p46ukDvr322+j0yJSf/Pa61oKencHir48xqhScMS8sqcCd5G0NPyNrJmYHQtNTjWyZwIZNvo3+T680JlSvRpw97j5I7tOq3P7K2/IRGCvB3CosYY1xoXd71mjL0L6boMVJ5i6nhF85wokVO3MvsRZvqfTNC4fbzyTM31Bsw6ePdv73pcwQvE8I6si50gmOXeU8XV/bNYfdQ7BPA8Id7M72N9ZKvbwHrpA2u19g8kZZbl3tVU81FWiABwt6xwF4/fpFA/6aO/tQLBBR+bJKbbab6TKWXGQRVx2mr83ux16iKUNRkvY0wJz3DIr5X1j4uWgn4nK7VicbEoL4mxgLZbu3WDYr5ltMyV9sxdZdaEtqJRD4WCepInbFZIK7mWzdrCvLxc1RUxy8dX8hwD3O+3MgIA9H8G+LEOt0gafbm2pdjejgt70OkbdOszOUYUq13lyOgmoSxZzs1ko5dweXEGdyXy1/UtkhxbM83lrxLG5UtWOdmZQ/AitlCAVjF1qV8QEDQSq4OpAfK0i1NFO07snCg4A==";
            strArrIP = DES.DecryptDES(strIP, DES.strDESKey).Split('|');
            IPCount = strArrIP.Length;
            IPIndex = 0;

            _sdIP = new SortedList<String, long>();
        }
     
        public void Ping()
        {
            //远程服务器IP  
            string ipStr = strArrIP[IPIndex];
            //构造Ping实例  
            Ping pingSender = new Ping();
            //Ping 选项设置  
            PingOptions Options = new PingOptions();
            Options.DontFragment = true;
            //测试数据  
            string strSendData = "12306BOT";
            byte[] buffer = Encoding.ASCII.GetBytes(strSendData);

            //调用同步 send 方法发送数据,将返回结果保存至PingReply实例  
            PingReply PR = pingSender.Send(ipStr, iTimeLimit, Encoding.ASCII.GetBytes(strSendData), Options);
            if (PR.Status == IPStatus.Success)
            {
                if (!_sdIP.ContainsKey(ipStr))
                {
                    _sdIP.Add(ipStr, PR.RoundtripTime);
                }
                else
                {
                    _sdIP[ipStr] = PR.RoundtripTime;
                }
            }
        }

        public void AddIPIndex()
        {
            IPIndex = (IPIndex + 1) % IPCount;
        }
    }
}
